package com.lyn.pluginbazaar.service;

import com.alibaba.fastjson.JSONObject;
import com.lyn.pluginbazaar.api.PluginAdapter;
import com.lyn.pluginbazaar.dao.plugin.Plugin;
import com.lyn.pluginbazaar.dao.plugin.PluginDao;
import com.lyn.pluginbazaar.entity.AddPlugin;
import com.lyn.pluginbazaar.entity.PagingQuery;
import com.lyn.pluginbazaar.entity.Result;
import com.lyn.pluginbazaar.entity.UpdatePlugin;
import com.lyn.pluginbazaar.utils.JpaUtil;
import com.lyn.pluginbazaar.utils.ObjectToObjectUtil;
import com.lyn.pluginbazaar.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class PluginService implements PluginAdapter {

    @Autowired
    private PluginDao pluginDao;

    @Override
    public Result addPlugin(AddPlugin addPlugin) {
        if(pluginDao.findByName(addPlugin.getName())!=null){
            return Result.FAIL("插件名称已经存在!");
        }
        if (pluginDao.findByPluginFileName(addPlugin.getPluginFileName())!=null){
            return Result.FAIL("插件文件名称已经存在!");
        }
        Plugin plugin = new Plugin();
        ObjectToObjectUtil.metastasis(addPlugin, plugin);
        plugin.setTime(System.currentTimeMillis());
        boolean save = JpaUtil.save(pluginDao, plugin);
        if (!save) {
            return Result.FAIL("添加失败!");
        }
        return Result.SUCCESS("添加插件成功!");
    }

    @Override
    public Result deletePlugin(Long id) {
        boolean delete = JpaUtil.delete(pluginDao, Plugin.class, id);
        if (!delete) {
            return Result.FAIL("删除失败!");
        }
        return Result.SUCCESS("删除成功!");
    }

    @Override
    public Result updatePlugin(UpdatePlugin updatePlugin) {
        Plugin plugin = new Plugin();
        ObjectToObjectUtil.metastasis(updatePlugin, plugin);
        plugin.setTime(System.currentTimeMillis());
        boolean update = JpaUtil.update(pluginDao, plugin);
        if (!update) {
            return Result.FAIL("修改失败!");
        }
        return Result.SUCCESS("修改成功!");
    }

    @Override
    public Result pagingQuery(PagingQuery pagingQuery) {
        List<Plugin> pluginList = JpaUtil.pagingQuery(pluginDao, Plugin.class, pagingQuery);
        if (pluginList == null || pluginList.isEmpty()) {
            return Result.FAIL("查询失败!");
        }
        for (Plugin plugin:pluginList){
            plugin.setDate(TimeUtil.getTime(plugin.getTime()));
        }
        long count = JpaUtil.count(pluginDao, Plugin.class, pagingQuery);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("pluginData",pluginList);
        jsonObject.put("total",count);
        return Result.SUCCESS("查询成功!", jsonObject);
    }

    @Override
    public Result count(PagingQuery pagingQuery) {
        long count = JpaUtil.count(pluginDao, Plugin.class, pagingQuery);
        return Result.SUCCESS("查询成功!", count);
    }
}
